
package com.treasure.service.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.treasure.service.BaseService;
import com.treasure.service.commons.lang.util.BeanUtil;
import com.treasure.service.commons.lang.util.StringUtil;
import com.treasure.service.constant.Constants;
import com.treasure.service.dto.PrepareResult;
import com.treasure.service.dto.TUserInfoDto;
import com.treasure.service.enums.CodeEnum;
import com.treasure.service.third.utils.TokenConfig;
import com.treasure.service.third.utils.UserToken;
import com.treasure.service.result.ResponseResult;
import com.treasure.service.user.service.UserService;
import com.treasure.service.third.utils.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author <a href="mailto:19919866605@163.com">Pan Xinwen</a>
 * @version 1.0 2018年5月29日 上午10:18:58
 */
@Service
public class UserServiceImpl extends BaseService implements UserService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RestClient restClient;

    @Value("${treasure.rest.service.third}")
    private String thirdUrl;

    @Autowired
    RestTemplate restTemplate;

    @Override
    public TUserInfoDto createWechatUser(TUserInfoDto user) {
        TUserInfoDto dto = restClient.post(this.getGateway()+"/userInfo/v1/createWechatUser",user,TUserInfoDto.class);
        return dto;
    }

    @Override
    public TUserInfoDto getUserInfoByUnionid(String openId) {

        TUserInfoDto dto = new TUserInfoDto();

        dto.setUnionid(openId);

        dto =restClient.post(this.getGateway()+"/userInfo/v1/getUserInfo",dto,TUserInfoDto.class);
        logger.info("获取用户基本信息{}",dto==null?"":JSON.toJSONString(dto));
        return dto;
    }


    @Override
    public TUserInfoDto updateUserInfo(TUserInfoDto user) {

        TUserInfoDto dto = restClient.post(this.getGateway()+"/userInfo/v1/updateUserInfo",user,TUserInfoDto.class);

        return dto;

    }

    @Override
    public PrepareResult dredgeMember(Long userId, Long couponId, Integer payType) {

        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        if(!StringUtil.isEmpty(couponId)){
            map.put("couponId",couponId);
        }
        map.put("payType",1);

        PrepareResult prepareResult = restClient.post(this.getGateway()+"/userInfo/v1/dredgeMember",map,PrepareResult.class);

        return prepareResult;
    }

    @Override
    public void bindingRelation(String openId, String inviteCode) {
        Map<String,Object> map = new HashMap<>();
        map.put("openId",openId);
        map.put("inviteCode",inviteCode);

        restClient.post(this.getGateway()+"/userInfo/v1/bindingRelation",map,PrepareResult.class);
    }

    @Override
    public Map getMyCenter() {

        UserToken userToken = TokenConfig.getTokenByHeader();
        TUserInfoDto dto = new TUserInfoDto();
        dto.setUserId(userToken.getUserId());
        dto=restClient.post(this.getGateway()+"/userInfo/v1/getUserInfo",dto,TUserInfoDto.class);
        logger.info("获取用户基本信息{}",dto==null?"":JSON.toJSONString(dto));

        Map<String,Object> map = new HashMap<>();
        map.put("headPortrait",dto.getHeadimgurl());
        map.put("userId",dto.getUserId());
        map.put("rank",Constants.Grade.getValue(dto.getGrade()));
        map.put("grade",dto.getGrade());
        map.put("name",dto.getNickname());
        map.put("isAuthName",dto.getIsAuthName()?1:0);


        //Todo 统计用户返利金额
        Map result = restClient.post(this.getGateway()+"/commission/v1/getStatistics",dto,Map.class);
        map.putAll(result);

        return map;
    }

    @Override
    public ResponseResult registerAndLogin(String phonenumber, String authCode) {

        Map<String,Object> map = new HashMap<>();

        UserToken userToken = TokenConfig.getTokenByHeader();
        TUserInfoDto tUserInfoDto = new TUserInfoDto();
        tUserInfoDto.setPhonenumber(phonenumber);
        if (userToken != null){
            tUserInfoDto.setUserId(userToken.getUserId());
        }

        tUserInfoDto = restClient.post(this.getGateway()+"/userInfo/v1/registerAndLogin",tUserInfoDto,TUserInfoDto.class);

        map = new HashMap<>();
        if (userToken == null){
            UserToken tokenId = TokenConfig.addToken(BeanUtil.copy(tUserInfoDto, UserToken::new));
            map.put("token",tokenId);
        }


        return new ResponseResult(CodeEnum.SUCCESS,map);

    }


    @Override
    public ResponseResult perfectInfo(String cardNumber, String cardName,String phoneNumber) {

        UserToken userToken = TokenConfig.getTokenByHeader();
        TUserInfoDto dto = new TUserInfoDto();
        dto.setUserId(userToken.getUserId());
        dto.setCardName(cardName);
        dto.setCardNumber(cardNumber);
        dto.setPhonenumber(phoneNumber);

        ResponseResult result = restClient.post(this.getGateway()+"/userInfo/v1/perfectInfo",dto,ResponseResult.class);

        if (result.getCode().equals(CodeEnum.SUCCESS.getCode())){
            userToken.setCardName(cardName);
            userToken.setCardNumber(cardNumber);
            TokenConfig.updateToken(userToken);
        }

        return result;
    }
}

